#include "defaults.h"
#include "triangle.h"
#include "edge.h"

SEdge::SEdge(Attribute& attribute, size_t id) :  ElementImplementation<SEdge>(attribute, id), a(0), b(0), triangle(0), neighbor(0)  {

}

SEdge::SEdge(Node* v0, Node* v1, Attribute& attribute, size_t id) : ElementImplementation<SEdge>(attribute, id) {
	triangle = 0;
	neighbor = 0;
	a = v0;
	b = v1;
}

void SEdge::Init(Node* a, Node* b, STriangle* triangle, SEdge* neighbor) {
	this->a = a;
	this->b = b;
	this->triangle = triangle;
	this->neighbor = neighbor;
}

Vec3n SEdge::Direction(const std::string& attribute) const {
	Vec3n u = b->Get<Vec3n>(attribute) - a->Get<Vec3n>(attribute);
	normalize(u);
	return u;
}

Vec3n SEdge::Normal(const std::string& attribute) const {
	Vec3n tnormal = triangle->Normal(attribute);
	Vec3n direction = Direction(attribute);
	Vec3n normal = cross(tnormal, direction);
	normalize(normal);
	return normal;
}
	
Vec3n SEdge::Center(const std::string& attribute) const {
	return 0.5 * (b->Get<Vec3n>(attribute) + a->Get<Vec3n>(attribute));
}

nfloat SEdge::Parameter(const Vec3n& P, size_t target) const {
	Vec3n d1 = P - a->Get<Vec3n>("position");
	Vec3n d2 = b->Get<Vec3n>("position") - a->Get<Vec3n>("position");
	nfloat t = d1[0] / d2[0];
	std::cout << "IMPLEMENT FUNCTION PROPERLY!" << std::endl;
	return 0.0;
	//return a->Scalar(target) + t * (b->Scalar(target) - a->Scalar(target));
}

SEdge* AdjacentEdge(STriangle* t1, STriangle* t2) {
	for(size_t i = 0; i < 3; i++) {
		if(t1->edge[i]->neighbor && t1->edge[i]->neighbor->triangle == t2)
			return t1->edge[i];
	}
	return 0;
}

